package com.c0nflict.server;

import java.util.Date;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;

import com.mysql.jdbc.ResultSet;

public class Player {
	/*
	 * Player types 0 = blocked (unoccupiable) 1 = empty 2 = nobody (place
	 * holder) 3 = player
	 */
	final static int OT_BLOCKED = 1;
	final static int OT_EMPTY = 2;
	final static int OT_NOBODY = 3;
	final static int OT_PLAYER = 4;
	final static int OT_BLACKHOLE = 5;
	private Table table = null;
	
	public void setTable(Table t) {
		boolean doreqs = false;
		
		if (table == null) doreqs = true;
		table = t;
		
		scriptToFriends(getFriendPoke(1), 1);
		ScriptBuffer s = new ScriptBuffer();
		if (doreqs) {
			Collection<Player> remdup = new HashSet<Player>();
			for (Player p : friendReqs) {
				if (friendList.contains(p)) 
					remdup.remove(p);
				else
					s.appendScript("pfreq('" + p.getName() + "');");
			}
			
			for (Player p : remdup) friendReqs.remove(p);
		}
		
		for (Player p : friendList) {
			if (p.friendList.contains(this));
			s.appendScript(p.getFriendPoke(1));
		}
		
		if (currentSession != null)
			currentSession.addScript(s);
	}
	
	public Table getTable() { return table; }
	private String inviteid = null;
	private String avatarStr = null;
	
	public String getInviteId() {
		return inviteid;
	}
	
	public void removeFriend(Player friend) {
		if (this.friendList.contains(friend)) {
			for (int x = 0; x < friends_db.length; x++) {
				if (friends_db[x].equals("" + friend.getDbId())) {
					friends_db[x] = "";
				}
			}
			
			this.friendList.remove(friend);
			this.saveFriends();			
		}
		
		if (this.friendReqs.contains(friend)) {
			for (int x = 0; x < friendreq_db.length; x++) {
				if (friendreq_db[x].equals("" + friend.getDbId())) {
					friendreq_db[x] = "";
				}
			}
			
			this.friendReqs.remove(friend);
			this.saveFriendReqs();			
		}
		
		if (friend == null) return;
		
		currentSession.addScript(new ScriptBuffer(friend.getFriendPoke(2)));
		friend.getSession().addScript(new ScriptBuffer(this.getFriendPoke(2)));
		if (friend.friendReqs.contains(this)) {
			friend.friendReqs.remove(this);
			friend.saveFriendReqs();			
		}
		
		if (friend.friendList.contains(this)) {
			friend.friendList.remove(this);
			friend.saveFriends();
		}
	}
	
	public void setInviteId(String i) {
		inviteid = i;
		if (dbId > 0) {
			tables.updateSQL("UPDATE dq_invite SET new_user_id=" + dbId + " where inviteid='" + i + "';");
		}
	}
	
	public boolean automaton = false;
	public Vector<Player>friendList = new Vector<Player>();
	public Vector<Player>friendReqs = new Vector<Player>();
	
	public String vectorToString(Vector<Player> in, String[] db) {
		StringBuffer out = new StringBuffer(":");
		
		for (int x = 0; x < in.size(); x++) {
			try { 
				out.append(in.get(x).getDbId()).append(":");
			} catch (Exception e) {}
		}
		
		for (int x = 0;x < db.length; x++) {
			if (!db[x].equals("") && out.indexOf(":" + db[x] + ":") == -1) {
				out.append(db[x]).append(":");				
			}
		}
		
		return out.toString();
	}
	
	private String[] friends_db = null;
	private String[] friendreq_db = null;
	
	public Vector<Player> stringToOnlinePlayers(String in) {
		//FIXME this can be optimized by sorting sessionmaps 
		//and database strings by dbid.  if we ever need to.
		Vector<Player> out = new Vector<Player>();
		if (in==null) return out;
		String[] temp = in.split(":");
		for (Player p : tables.userSessions.keySet()) {
			for (int z=0;z<temp.length;z++) {
				if (!temp[z].trim().equals(""))
					if (p.getDbId() == new Integer(temp[z]).intValue()) {
							if (!out.contains(p))
								out.add(p);
			}
			}
		}
		return out;
	}
	
	public void loadFriendLists() {
		if (tables == null) tables = TableManager.tables;
		String friends = tables.singleValueSql("select friends from dq_user where user_id=" + dbId + ";");
		String reqs = tables.singleValueSql("select friendreqs from dq_user where user_id=" + dbId + ";");
		if (friends == null) friends = "";
		if (reqs == null) reqs = "";
		
		friends_db = friends.split(":");
		friendreq_db = reqs.split(":");
		//FIXME we dont need real player objects for requests -- lets just use
		//string names -- that way we minimize database killing
		friendList = stringToOnlinePlayers(friends);
		friendReqs = stringToOnlinePlayers(reqs);
		//broadcast to your friends that you are online.
		saveFriendReqs();
		saveFriends();
	}
	
	private int lastNewsId = 0;
	
	public int getLastNewsId() { return lastNewsId; }
	public void setLastNewsId(int id) { 
		lastNewsId = id;
		tables.updateSQL("update dq_user set news_id = " + id + " where user_id = " + dbId);
	}
	
	public void setNews() { setNews(lastNewsId); }
	
	public void setNews(int newsId) {
		StringBuffer buf = new StringBuffer();
		
		//TODO Can be improved in the future if less db access is desired
		//by moving maxNewsId into TableManager class and caching all the news in it
		//will also require that news admin be done through the class so updates are reflected
		if (tables == null) tables = TableManager.tables;
		String result = tables.singleValueSql("select max(id) from dq_news");
		int maxNewsId = new Integer(result).intValue();
		
		if (newsId > lastNewsId)
			setLastNewsId(newsId);
		
		ScriptBuffer sp = new ScriptBuffer();
		
		if (lastNewsId < maxNewsId)
			sp.appendScript("document.getElementById('sbac3').style.backgroundColor = '#e00';");
		else
			sp.appendScript("document.getElementById('sbac3').style.backgroundColor = '#333';");
		
		if (newsId > 0)
			buf.append("&nbsp;&nbsp;<a href=\"#\" onclick=\"goto_news(0); return false;\" title=\"First news post\">&lt;&lt;</a>&nbsp&nbsp;<a href=\"#\" onclick=\"goto_news(" + (newsId - 1) + "); return false;\" title=\"Previous news post\">&lt;</a>");
		
		if (newsId < maxNewsId)
			buf.append("&nbsp;&nbsp;<a href=\"#\" onclick=\"goto_news(" + (newsId + 1) + "); return false;\" title=\"Next news post\">&gt;</a>&nbsp&nbsp;<a href=\"#\" onclick=\"goto_news(" + maxNewsId + "); return false;\" title=\"Latest news post\">&gt;&gt;</a>");

		sp.appendScript("update_contents('sb_news_controls', '" + buf.toString() + "');");
		
		String news = tables.singleValueSql("select news from dq_news where id = " + newsId);
		sp.appendScript("update_contents('sb_news', '" + news + "');");
		
		currentSession.addScript(sp);
	}
	
	public void setInfo() {
		ScriptBuffer sp = new ScriptBuffer();
		sp.appendScript("set_player_info('" + name + "', " + elo + ");");
		if (currentSession!=null)
			currentSession.addScript(sp);
	}
	
	private Map<Integer, Integer> _tableRatings = new HashMap<Integer,Integer>();
	
	public void loadTableRatings() {
		if (tables==null) tables = TableManager.tables;
		String rt = tables.singleValueSql("select table_ratings from dq_user where user_id="+getDbId()+";");
		if (rt==null) return;
		String[] ratings = rt.split(",");
		_tableRatings.clear();
		for (int x=0;x<ratings.length;x++) {
			try {
			String[] pair = ratings[x].split(":");
			if (pair.length==2) {
			_tableRatings.put(new Integer(pair[0]), new Integer(pair[1]));
			tables.putTableRating(new Integer(pair[0]).intValue(), new Integer(pair[1]).intValue());
			}
			} catch (Exception e) {e.printStackTrace();}
		}
	}
	
	public void saveTableRatings() {
		StringBuffer saveStr = new StringBuffer();
		for (Integer tableid : _tableRatings.keySet()) {
			saveStr.append(tableid).append(":").append(_tableRatings.get(new Integer(tableid))).append(",");
		}
		
		tables.updateSQL("update dq_user set table_ratings='" + saveStr.substring(0, saveStr.length() - 1) + "' where user_id=" + dbId);
	}
	
	public void putTableRating(long JSID,int rating) {
		Table t = tables.getTableByJSID(JSID);
		if (t == null) return;
		putTableRating(t, rating);
	}
	
	public void putTableRating(Table t,int rating) {
		_tableRatings.remove(new Integer(t.getId()));
		_tableRatings.put(new Integer(t.getId()), new Integer(rating));
		tables.putTableRating(t.getId(), rating);
		saveTableRatings();		
	}
	
	public void resetTableRatings() {
		for (Integer i : _tableRatings.keySet()) {
			tables.putTableRating(i.intValue(), _tableRatings.get(i).intValue());
		}
	}
	
	public int getTableRating(long JSID) {
		Table t = tables.getTableByJSID(JSID);
		if (t == null) return 0;
		Integer rating = _tableRatings.get(new Integer(t.getId()));
		if (rating == null) return 0;
		return rating.intValue();
	}
	
	public String getFriendPoke(int status) {
		if (table == null) return "";
		//status 1 - going online / map change / isplayer change
		//status 2 - signing off
		StringBuffer p = new StringBuffer("pf('");
		p.append(name).append("','");
		p.append(table.getName()).append("',");
		p.append(table.getJSID()).append(",");
		p.append(status).append(",");
		p.append(isPlayer() ? 1 : 0).append(");");
		return p.toString();
	}
	public void scriptToFriends(String script,int status) {
		ScriptBuffer s = new ScriptBuffer(script);
		for (int x = 0; x < friendList.size(); x++) {
			Player f = friendList.get(x);
			if (f != this && !f.getName().equals(name)) {
				if (status == 1) if (!f.friendList.contains(this)) f.friendList.add(this);
				if (!f.getSession().isInvalidated() && f.friendList.contains(this))
					f.getSession().addScript(s);
				if (status == 2) {
					f.friendList.remove(this);
				}
			}
		}
	}
	
	public void saveFriends() {
		String update = "update dq_user set friends='" + vectorToString(friendList,friends_db) + "' where user_id=" + dbId + ";";
		tables.updateSQL(update);
	}
	
	public void saveFriendReqs() {
		String update = "update dq_user set friendreqs='" + vectorToString(friendReqs,friendreq_db) + "' where user_id=" + dbId + ";";
		tables.updateSQL(update);
	}
	
	public void addFriendReq(Player from) {
		friendReqs.add(from);
		ScriptBuffer s = new ScriptBuffer("pfreq('"+from.getName()+"');");
		currentSession.addScript(s);
		saveFriendReqs();
	}
	public void addFriend(Player from) {
		friendList.add(from);
		if (friendReqs.contains(from)) friendReqs.remove(from);
		
		if (from.friendList.contains(this)) {
			ScriptBuffer s = new ScriptBuffer(from.getFriendPoke(1));
			currentSession.addScript(s);
		    s = new ScriptBuffer(this.getFriendPoke(1));
			from.getSession().addScript(s);
		}
		
		saveFriends();
	}
	public boolean isAutomaton() { return automaton; }
	
	public void setAutomaton() {
		this.dbId = 4178;
		automaton = true;
		this.currentSession = new RobotSession();
		if (tables.automatonElos.size() == 0) {
			this.elo = 50;	
		} else {
			int re = tables.R.randomBaseZero(tables.automatonElos.size());
			this.elo = tables.automatonElos.get(re);
			//if (this.elo > 60) this.elo=50;
			tables.automatonElos.remove(re);
		}
	}

	String eol = System.getProperty("line.separator");

	HttpSession http = null;
	public void setHttpSession(HttpSession s) {
		this.http = s;
	}
	public HttpSession getHttpSession() {
		return this.http;
	}
	
	private String ipAddr = "";
	private int dbId = -1; // Player's database id
	private String name = ""; // Player's name
	private int playerType = 0; // Type of player (see above for types)
	private int totalDice = 0; // Total dice in this game
	private int rank = 0; // Specific game rank
	private int overallRank = 0; // Overall game rank
	private int orderId = -1; // Player's order in game

	private int hasPlayed = 0;

	private Vector<TableSquare> squares = new Vector<TableSquare>(); // Player's squares

	private boolean requestStart = false; // Whether the player has checked the "Start Game" box

	private int diceReserves = 0; // Extra dice available to player

	private int turnsIdle = 0; // Number of turns the player has not made a move
	private int movableAreas = 0;
	
	public void setMovableAreas(int num) {
		// Maybe improve this so code only runs on tables with offturn movement
		if (num == 0) {
			ScriptBuffer s = new ScriptBuffer();
			s.appendScript("document.getElementById('offturn_moves').innerHTML='';");
			currentSession.addScript(s);
		}
		
		if (num == 0 && fromSquare != null) {
			ScriptBuffer s = new ScriptBuffer();
			s.appendScript("undepress_square(" + fromSquare.getId() + ");");
			fromSquare = null;
			currentSession.addScript(s);			
		}
		
		movableAreas = num;
	}

	public TableSquare fromSquare = null;
	
	public int moveArmies(TableSquare selected) {
		ScriptBuffer s = new ScriptBuffer();
		Table t = tables.getTable(this);
		
		if (movableAreas <= 0) {
			s.appendScript("sendStatus('<b>You may not move any more armies.</b><br>');");
			currentSession.addScript(s);
			return 0;
		}
		
		if (fromSquare == null && selected.getOwner() == this && ((int)selected.getDice() * t.getMovableDicePercent()) >= 1) {
			fromSquare = selected;
			s.appendScript("depress_square(" + selected.getId() + ");");
			currentSession.addScript(s);
			return movableAreas;
		} else if (fromSquare != null && (fromSquare == selected || fromSquare.getOwner() != this)) {
			s.appendScript("undepress_square(" + selected.getId() + ");");
			fromSquare = null;
			currentSession.addScript(s);
			return movableAreas;
		} 
		else if (selected.getOwner() == this && fromSquare != null) {
			// check if we are adjacent, if we are, move dice.
			Vector<Integer> adj = t.adjacentSquares(fromSquare.getId(), false);
			boolean isAdj = false;
			for (int z = 0; z < adj.size(); z++) {
				int square = ((Integer) adj.get(z)).intValue();
				if (square == selected.getId()) {
					isAdj = true;
					break;
				}
			}
			
			if (isAdj) {
				int howmany = (int)(fromSquare.getDice() * t.getMovableDicePercent());
				if (selected.getDice() + howmany > t.getMaxDicePerSquare())
					howmany = t.getMaxDicePerSquare() - selected.getDice();
				if (howmany <= 0) return 0;
				
				movableAreas--;
				fromSquare.addDice(-howmany);
				selected.addDice(howmany);
				// Update offturn moves remaining message
				ScriptBuffer s2 = new ScriptBuffer();
				s2.appendScript("document.getElementById('offturn_moves').innerHTML='Offturn moves remaining: " + movableAreas + "';");
				currentSession.addScript(s2);
				
				StringBuffer buf = new StringBuffer();
				buf.append(fromSquare.getId()).append(",").append(selected.getId()).append(",").append(getColor());
				t.logger.logEvent(name, "reinfm", buf.toString());
				
				buf = new StringBuffer();
				buf.append("refresh_squares(").append(t.getJSID()).append(",");
				buf.append(fromSquare.getId()).append(",");
				buf.append(selected.getId()).append(",");
				buf.append(getColor()).append(",");
				buf.append(getColor()).append(",");
				buf.append(fromSquare.getDice()).append(",");
				buf.append(selected.getDice()).append(",[],[]);");
				s.appendScript(buf.toString());
				tables.sendJavascript(t, s);
				
				fromSquare = null;
			}
		}
		
		return movableAreas;
	}
	
	TableManager tables = null;

	public String email = "";

	private String preferences = "";

	public Vector<TableSquare> getSquares() {
		return squares;
	}

	public int getOwnerType() {
		return playerType;
	} 

	public String getIPAddr() {
		return ipAddr;
	}

	public void setIPAddr(String addr) {
		ipAddr = addr;
	}

	public boolean isBlocked() {
		return (playerType == OT_BLOCKED);
	}

	public boolean isEmpty() {
		return (playerType == OT_EMPTY);
	}

	public boolean isNobody() {
		return (playerType == OT_NOBODY);
	}

	public boolean isPlayer() {
		return (playerType == OT_PLAYER);
	}
	public boolean isBlackHoled() {
		return (playerType == OT_BLACKHOLE);
	}

	public void setBlocked() {
		playerType = OT_BLOCKED;
		orderId = -2;
	}

	public void setEmpty() {
		if (isBlocked()) return;
		playerType = OT_EMPTY;
		orderId = -1;
	}

	public void setNobody() {
		if (isBlocked()) return;
		playerType = OT_NOBODY;
		orderId = -1;
		setTotalEarned(0);
		scriptToFriends(getFriendPoke(1),1);
	}
	public void setNobodyOverride() {
		//if (isBlocked()) return;
		playerType = OT_NOBODY;
		orderId = -1;
		setTotalEarned(0);

	}
	public void setNobody(int id) {
		if (isBlocked()) return;
		playerType = OT_NOBODY;
		orderId = id;
		setTotalEarned(0);
		scriptToFriends(getFriendPoke(1),1);
	}
	private int totalEarnedDice = 0;
	public void setTotalEarned(int dice) {
		totalEarnedDice=dice;
	}
	public void addTotalEarned(int dice) {
		totalEarnedDice+=dice;
	}
	public int getTotalEarned() {
		return totalEarnedDice;
	}
	public void setPlayer(int id) {
		if (isBlocked()) return;
		scriptToFriends(getFriendPoke(1),1);
		playerType = OT_PLAYER;
		orderId = id;
		setTotalEarned(0);
	}

	/*
	 * Admin levels 
	 * 0  = Generic user (default value, in case entry exists) 
	 * 1  = User admin 
	 * 10 = Game admin
	 * 99 = Super admin
	 */
	final static int ADMIN_NONE = 0;
	final static int ADMIN_USER = 1;
	final static int ADMIN_GAME = 10;
	final static int ADMIN_SUPER = 99;

	private int adminLevel = ADMIN_NONE;
	private int dbAdminLevel = 0;

	public int getAreaCount() {
		return squares.size();
	}

	public void resetAreas() {
		squares.clear();
		totalDice = 0;
	}

	public String getNameRoster() {
		String ret = name.replace(" ", "&nbsp;");
		if (this.getAdminLevel() > 0) {
			ret = "<span class=\"MP\">MP</span>" + ret;
		} else if (this.isAutomaton()) {
			ret = "<span class=\"AI\">AI</span>" + ret;
			
		}
		
		return ret;
	}

	public int getPlusDice() { return diceReserves; }
	public void setPlusDice(int dice) { diceReserves = dice; }

	public String getName() { return name; }
	public void setName(String name) { this.name = name; }

	public boolean getRequestStart() { return requestStart; }
	public void setRequestStart(boolean request) { 
		requestStart = request; 
		//System.out.println(getTable().getName()+","+getColor());
		if (getColor()>0 && getTable()!=null)
			TableManager.tables.sendJavascript(this.getTable(),"set_play_now("+this.getColor()+","+request+");");	
	}

	public int getRank() { return rank; }
	public void setRank(int rank) { this.rank = rank; }

	public int getOverallRank() { return overallRank; }
	public void setOverallRank(int rank) { overallRank = rank; }

	private int elo = 0; // Player's initial ELO
	public int getELO() { return elo; }
	public void setELO(int elo) {
		// ELO can not drop below 0
		if (elo < 0)
			elo = 0;

		this.elo = elo;
		if (tables==null) tables = TableManager.tables;
		tables.setELO(this, elo, preferences);
		setInfo();
	}

	public void addArea(TableSquare square) {
		squares.add(square);
		addDice(square.getDice());
	}

	public void removeArea(TableSquare square) {
		squares.remove(square);
		addDice(-square.getDice());
	}

	public boolean hasPlayed() {
		if (hasPlayed == -1)
			return false;
		return true;
	}

	public int getOrderId() { return orderId; }
	public void setOrderId(int id) { orderId = id; }

	public int getColor() { return orderId + 1; }

	public int getTotalDice() { return totalDice; }

	public void addDice(int dice) {
		totalDice += dice;

		if (totalDice < 0)
			totalDice = 0;
	}

	public int getDbId() { return dbId; }

	public void unIdle() { turnsIdle = 0; }
	public void idle() { turnsIdle++; }

	public boolean shouldAutoFlag() { return (turnsIdle > 4); }

	private ScriptSession currentSession = null;
	public ScriptSession getSession() { return currentSession; }
	public void setSession(ScriptSession s) { currentSession = s; }

	public Player(String username, TableManager tm) {
		name = username;
		tables = tm;
		
	}
	public void setAvatar (String in) {
		avatarStr = in;
	}
	public Player(ScriptSession username, TableManager tm,HttpSession http, HttpServletRequest req) {
		tables = tm;
		setHttpSession(http);
		setHttpRequest(req);
		tables.watchernum++;
		setName("watcher"+tables.watchernum);
		setSession(username);
		setBlocked();
		avatarStr = "//c0nflict.com/av/youarehere.jpg";
		
	}

	public int getAdminLevel() { return adminLevel; }
    public void clearAdminLevel() {	adminLevel = ADMIN_NONE; }
    
    public int getDbAdminLevel() { return dbAdminLevel; } 
    
    public void setDbAdminLevel() {
    	try {
    	String levelStr = tables.singleValueSql("select admin_level from dq_user where user_id = " + dbId);
    	dbAdminLevel = new Integer(levelStr).intValue();
    	}
    	catch (Exception e) {}
    }
    
	public void setAdminLevel() {
		setDbAdminLevel();
		adminLevel = dbAdminLevel;
		System.out.println("User " + name + " has admin level of " + adminLevel);
	}

	public boolean isNotAdmin() {
		return (adminLevel == ADMIN_NONE);
	}
	public int lastMessageRead = -1;
	public boolean isAdmin() { return (adminLevel > ADMIN_NONE); }
	public boolean isUserAdmin() { return isAdmin(); }
	public boolean isGameAdmin() { return (adminLevel > ADMIN_USER); }
	public boolean isSuperAdmin() { return (adminLevel > ADMIN_GAME); }

	public String getPreferences() { return preferences; }
	public void setPreferences(String prefs) {
		if (prefs.contains(";")
				|| prefs.contains("GO")
				|| prefs.contains("\n")) return;
		
		String[] testpairs = prefs.split(",");
		for (int x=0;x<testpairs.length;x++) {
			String testpair[] = testpairs[x].split(":");
			if (testpair[0].length()>3) return;
		}
			
		
		preferences = prefs;
		
		tables.setPreferences(this,prefs);
	}

	//private HttpServletRequest httpRequest = null;
	//public HttpServletRequest getHttpRequest() { return httpRequest; }
	private String userAgent = null;
	private String reqUser = null;
	//private String ipAddr = null;
	public void setHttpRequest(HttpServletRequest req ) { 
		userAgent = req.getHeader("user-agent");
		ipAddr = req.getRemoteHost();
		reqUser = req.getRemoteUser();
		} 
	public String getUserAgent() {
		return userAgent;
	}
	public String getRemoteUser() {
		return reqUser;
	}
	public Player(TableManager tables, String username, String password, ScriptSession whoisthis) {
		email = username;
		this.tables = tables;
		name = "-1";
		this.setSession(whoisthis);

		try {
			ResultSet rs = tables.loginUserPass(this.email, password);

			while (rs.next()) {
				name = rs.getString("username");
				dbId = rs.getInt("user_id");
				elo = rs.getInt("elo");
				hasPlayed = rs.getInt("has_played");
				preferences = rs.getString("preferences");
				lastNewsId = rs.getInt("news_id");
				lastMessageRead = rs.getInt("last_privmsg");
				avatarStr = rs.getString("user_avatar");
				int avatarType = rs.getInt("user_avatar_type");
				if (avatarStr != null && avatarStr != "") {
					if (avatarStr.indexOf("http://")==-1) 
						avatarStr = "http://c0nflict.com/forum/images/avatar/"+avatarStr;
				}  else {
					avatarStr = "http://c0nflict.com/war/images/0.png";
				}
				System.out.println("rs:" + name + "(" + dbId + ")");
			}
			
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		setDbAdminLevel();
		setNobody();
	}
	public String getAvatarHtml() {
		return "<img style=\"margin-left: -2px; float: left;\" height=48 width=48 src=\"" + avatarStr + "\">";
	}
	public Player(TableManager tables, String email, ScriptSession whoisthis) {
		this.email = email;
		this.tables = tables;
		name = "-1";
		this.setSession(whoisthis);

		try {
			ResultSet rs = tables.loginEmail(email);
			while (rs.next()) {
				name = rs.getString("username");
				dbId = rs.getInt("user_id");
				elo = rs.getInt("elo");
				preferences = rs.getString("preferences");
				lastNewsId = rs.getInt("news_id");
				lastMessageRead = rs.getInt("last_privmsg");
				avatarStr = rs.getString("user_avatar");
				int avatarType = rs.getInt("user_avatar_type");
				if (avatarStr != null && avatarStr != "") {
					if (avatarStr.indexOf("http://")==-1) 
						avatarStr = "http://c0nflict.com/forum/images/avatar/"+avatarStr;
				}  else {
					avatarStr = "http://c0nflict.com/war/images/0.png";
				}
				System.out.println("rs:" + name + "(" + dbId + ")");
			}
			
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		setDbAdminLevel();
		setNobody();
	}

	public String toXml() {
		StringBuffer buf = new StringBuffer("  <player id=");
		buf.append(getOrderId()).append(">").append(eol);

		buf.append("    <name>").append(name).append("</name>").append(eol);
		buf.append("    <rank>").append(getRank()).append("</rank>").append(eol);
		buf.append("    <overallRank>").append(getOverallRank()).append("</overallRank>").append(eol);
		buf.append("    <color>").append(getColor()).append("</color>").append(eol);
		buf.append("    <totalDice>").append(getTotalDice()).append("</totalDice>").append(eol);
		buf.append("    <areaCount>").append(getAreaCount()).append("</areaCount>").append(eol);
		buf.append("    </player>").append(eol);

		return buf.toString();
	}

	double PERSONALITY_ATTACK_PERCENT = .5;
	int PERSONALITY_ATTACK_MOD = 0;
	int PERSONALITY_RISK_IN_ATTACK = 4;
	int PERSONALITY_AGGRESSIVE = 3;
	int PERSONALITY_CAUTIOUS = 2;
	int PERSONALITY_RANDOM = 1;
	int PERSONALITY_TYPE = 3;
	
	public void setPersonality(int personalityType) {
		PERSONALITY_TYPE=personalityType;
		if (personalityType==PERSONALITY_RANDOM) personalityType=tables.R.randomBaseOne(2)+1;
		
		if (personalityType==PERSONALITY_AGGRESSIVE) {
			PERSONALITY_ATTACK_PERCENT = .85;
			PERSONALITY_RISK_IN_ATTACK = 1;
			PERSONALITY_ATTACK_MOD = 5;
		}
		else if (personalityType==PERSONALITY_CAUTIOUS) {
			PERSONALITY_ATTACK_PERCENT = .35;
			PERSONALITY_RISK_IN_ATTACK = 0;
			PERSONALITY_ATTACK_MOD = 1;
		}
		else {
			//else if (personalityType==PERSONALITY_RANDOM) {
			PERSONALITY_ATTACK_PERCENT = 1;
			PERSONALITY_RISK_IN_ATTACK = 1;
			PERSONALITY_ATTACK_MOD=1;
		}
	}
	
	private boolean afk = false;
	
	public boolean isAFK() { return afk; }
	public void setAFK() { afk = true; }
	public void setActive() { afk = false; }
	
	private Date lastActivity = new Date();
	
	public void tickActivity() {
		lastActivity = new Date();
	}
	
	public boolean checkActivity() {
		Date current = new Date();
		if (this.isAdmin() || this.isPlayer()) return true;
		
		//System.out.println("ACT CHECK "+current.toString()+" "+lastActivity.toString());
		int MINUTES = 15;
		if (current.getTime()-lastActivity.getTime()>MINUTES*60000) {
			return false;
		}
		return true;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {

	}
}
